import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:like_button/like_button.dart';
import 'package:live_music/components/common/FilePreviewPage.dart';
import 'package:live_music/components/common/PictureOverview.dart';
import 'package:live_music/components/ui/tag.dart';
import 'package:live_music/components/ui/theme.dart';
import 'package:live_music/models/moment_detail_model.dart';
import 'package:live_music/pages/detail/moment_detail.dart';
import 'package:live_music/pages/other/click_see_other.dart';
import 'package:live_music/services/operationServiece.dart';
import 'package:live_music/utils/cgq_utils.dart';
import 'package:live_music/utils/colors.dart';
import 'package:live_music/utils/contentParse.dart';
import 'package:live_music/utils/sp_utils.dart';
import 'package:live_music/utils/util.dart';

class MomentCard extends StatefulWidget {
  final MomentDetailModel momentListItem;
  final Function delMoment;
  final int index;
  final String fromPage;
  MomentCard(
      {Key key, this.momentListItem, this.index, this.delMoment, this.fromPage})
      : super(key: key);
  @override
  _MomentCardState createState() => _MomentCardState();
}

class _MomentCardState extends State<MomentCard>
    with SingleTickerProviderStateMixin {
  List options = ['删除'];
  MomentDetailModel _momentListItem;
  int userId;
  @override
  void initState() {
    super.initState();
    setState(() {
      _momentListItem = widget.momentListItem;
    });

    initData();
  }

  initData() async {
    Map<String, dynamic> localuserLogin = await SPUtil.getObject('userLogin');
    setState(() {
      userId = localuserLogin['userId'];
    });
  }

  @override
  Widget build(BuildContext context) {
    return InkWell(
        onTap: () => {Get.to(MomentDetailPage(id: _momentListItem.id))},
        child: Container(
          margin: const EdgeInsets.only(bottom: 4),
          decoration: BoxDecoration(
              border: Border(
            bottom: BorderSide(width: .5, color: WcaoTheme.outline),
          )),
          child: Padding(
            padding: const EdgeInsets.all(16),
            child: Row(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                InkWell(
                    child: SizedBox(
                      width: 44,
                      height: 44,
                      child: ClipRRect(
                        borderRadius: BorderRadius.circular(44),
                        child: CgqUtils.imageCache(
                            _momentListItem.userAvatarUrl,
                            fit: BoxFit.cover),
                      ),
                    ),
                    onTap: () {
                      Get.to(PageViewOther(userId: _momentListItem.userId));
                    }),
                Expanded(
                  child: Padding(
                    padding: const EdgeInsets.symmetric(horizontal: 8),
                    child: Column(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: [
                        Row(
                          mainAxisAlignment: MainAxisAlignment.spaceBetween,
                          children: [
                            Text(
                              _momentListItem.userName,
                              style: TextStyle(
                                color: WcaoTheme.base,
                                fontWeight: FontWeight.bold,
                                fontSize: WcaoTheme.fsL,
                              ),
                            ),
                            userId == _momentListItem.userId &&
                                    widget.fromPage == "userPage"
                                ? InkWell(
                                    onTap: () {
                                      return showModalBottomSheet<int>(
                                          isScrollControlled: false,
                                          context: context,
                                          shape: RoundedRectangleBorder(
                                            borderRadius:
                                                const BorderRadius.only(
                                              topLeft: Radius.circular(10),
                                              topRight: Radius.circular(10),
                                            ),
                                          ),
                                          builder: (BuildContext context) {
                                            return Container(
                                              constraints: BoxConstraints(
                                                  minHeight: 60,
                                                  maxHeight: 100),
                                              child: ListView.builder(
                                                itemBuilder:
                                                    (BuildContext context,
                                                        int index) {
                                                  return ListTile(
                                                      title:
                                                          Text(options[index]),
                                                      onTap: () {
                                                        if (index == 0) {
                                                          widget.delMoment(
                                                              widget.index);
                                                        }
                                                        Navigator.of(context)
                                                            .pop(index);
                                                      });
                                                },
                                                itemCount: options.length,
                                              ),
                                            );
                                          });
                                    },
                                    child: Container(
                                      width: 40,
                                      alignment: Alignment.centerRight,
                                      child: Image.asset(
                                        'assets/images/icons/more_select.png',
                                        color: Colors.grey[600],
                                        width: 20,
                                        height: 20,
                                      ),
                                    ),
                                  )
                                : Container()
                          ],
                        ),
                        Container(
                          margin: const EdgeInsets.only(top: 4),
                          child: Text(
                            getDateTime(_momentListItem.createTime),
                            style: TextStyle(
                              color: WcaoTheme.secondary,
                            ),
                          ),
                        ),
                        Container(
                          margin: const EdgeInsets.only(top: 12),
                          child: FormattedText(
                            _momentListItem.textContent,
                            style: TextStyle(
                              color: WcaoTheme.base,
                            ),
                            maxLines: 5,
                            overflow: TextOverflow.ellipsis,
                          ),
                        ),
                        _momentListItem.repostedMoment != null
                            ? InkWell(
                                onTap: () => {
                                      Get.to(MomentDetailPage(
                                          id: widget
                                              .momentListItem.repostMomentId))
                                    },
                                child: Container(
                                    decoration: BoxDecoration(
                                        color: Colors.grey[200],
                                        borderRadius: BorderRadius.circular(8)),
                                    padding: EdgeInsets.all(8),
                                    margin: EdgeInsets.only(top: 10, bottom: 6),
                                    child: Column(
                                      mainAxisAlignment:
                                          MainAxisAlignment.start,
                                      children: [
                                        Row(
                                          children: [
                                            Text(
                                                "@" +
                                                    widget
                                                        .momentListItem
                                                        .repostedMoment
                                                        .userName,
                                                style: TextStyle(
                                                  color: Colors.blueAccent,
                                                  fontSize: 14,
                                                  fontWeight: FontWeight.bold,
                                                )),
                                            Text(":",
                                                style: TextStyle(
                                                  color: Colors.grey,
                                                  fontSize: 14,
                                                  fontWeight: FontWeight.bold,
                                                )),
                                          ],
                                        ),
                                        Container(
                                          alignment: Alignment.centerLeft,
                                          child: _buildTypeItem(widget
                                              .momentListItem.repostedMoment),
                                        ),
                                        _momentListItem.repostedMoment.type ==
                                                "TEXT"
                                            ? Container(
                                                alignment: Alignment.centerLeft,
                                                margin: EdgeInsets.only(top: 8),
                                                child: FormattedText(
                                                  widget
                                                      .momentListItem
                                                      .repostedMoment
                                                      .textContent,
                                                  style: TextStyle(
                                                    color: WcaoTheme.base,
                                                  ),
                                                  maxLines: 5,
                                                  overflow:
                                                      TextOverflow.ellipsis,
                                                ),
                                              )
                                            : Container(),
                                      ],
                                    )))
                            : _buildTypeItem(_momentListItem),
                        _momentListItem.tagList != null
                            ? Container(
                                margin: const EdgeInsets.only(top: 12),
                                child: Wrap(
                                    spacing: 12,
                                    runSpacing: 6,
                                    children: _momentListItem.tagList.map((e) {
                                      return Tag(
                                        e.name,
                                        borderRadius: BorderRadius.circular(24),
                                        fontSize: 12,
                                        padding: const EdgeInsets.only(
                                          top: 2,
                                          bottom: 2,
                                          left: 8,
                                          right: 8,
                                        ),
                                        color: Colors.pink[300],
                                        backgroundColor: Colors.pink[50],
                                      );
                                    }).toList()),
                              )
                            : Container(),
                        Container(
                          margin: const EdgeInsets.only(top: 12),
                          child: Row(
                            crossAxisAlignment: CrossAxisAlignment.center,
                            mainAxisAlignment: MainAxisAlignment.spaceBetween,
                            children: [
                              // 分享
                              iconText(Icons.offline_share,
                                  _momentListItem.viewCount.toString()),

                              Row(
                                children: [
                                  InkWell(
                                      onTap: () => {},
                                      child: Row(
                                        children: [
                                          LikeButton(
                                              isLiked: _momentListItem.hasLiked,
                                              onTap: (isLiked) {
                                                return onTapLikeButton(
                                                    !isLiked);
                                              },
                                              size: 20,
                                              circleColor: CircleColor(
                                                  start: ColorRes.color_3,
                                                  end: ColorRes.color_3),
                                              likeBuilder: (isLike) {
                                                return isLike == true
                                                    ? Image.asset(
                                                        'assets/images/common/red_heart.webp')
                                                    : Icon(
                                                        Icons
                                                            .favorite_border_outlined,
                                                        size: 20,
                                                        color:
                                                            WcaoTheme.secondary,
                                                      );
                                              },
                                              bubblesColor: const BubblesColor(
                                                dotPrimaryColor:
                                                    ColorRes.color_3,
                                                dotSecondaryColor:
                                                    ColorRes.color_3,
                                                dotThirdColor: ColorRes.color_3,
                                                dotLastColor: ColorRes.color_3,
                                              )),
                                          Text(
                                            _momentListItem.likeCount
                                                .toString(),
                                            style: TextStyle(
                                                color: WcaoTheme.secondary),
                                          ),
                                        ],
                                      )),
                                  // 评论
                                  Container(
                                    margin: const EdgeInsets.only(left: 24),
                                    child: iconText(
                                      Icons.add_comment_outlined,
                                      _momentListItem.commentCount.toString(),
                                    ),
                                  ),
                                ],
                              )
                            ],
                          ),
                        ),
                      ],
                    ),
                  ),
                )
              ],
            ),
          ),
        ));
  }

  Future<bool> onTapLikeButton(bool isLiked) async {
    _momentListItem.hasLiked = isLiked;
    if (isLiked) {
      _momentListItem.likeCount++;
    } else {
      _momentListItem.likeCount--;
    }
    Map<String, dynamic> data = {
      "targetId": _momentListItem.id,
      "targetType": 'MOMENT',
    };
    if (isLiked) {
      await OperationServiece.like(data);
    } else {
      await OperationServiece.cancelLike(data);
    }
    setState(() {
      _momentListItem = _momentListItem;
    });
    return isLiked;
  }
}

Widget _buildTypeItem(MomentDetailModel momentListItem) {
  Widget typeItem;
  switch (momentListItem.type) {
    case "VIDEO":
      typeItem = _videoCover(momentListItem.video);
      break;
    case "IMAGE":
      typeItem = _buildImages(momentListItem.imageList);
      break;
    case "FILE":
      typeItem = _buildFile(momentListItem.file);
      break;
    default:
      typeItem = Container();
      break;
  }
  return typeItem;
}

_buildFile(FileClass file) {
  return Container(
    margin: const EdgeInsets.only(top: 8),
    padding: EdgeInsets.all(12),
    color: Colors.grey[100],
    child: ClipRRect(
        borderRadius: BorderRadius.circular(8),
        child: Row(children: [
          Container(
            margin: const EdgeInsets.only(right: 4),
            child: InkWell(
                onTap: () async {
                  // bool isInit = await FilePreview.tbsHasInit();
                  // if (!isInit) {
                  //   await FilePreview.initTBS();
                  // } else {
                  //   print('init');
                  // }
                  // await FilePreview.initTBS();
                  Get.to(FilePreviewPage(
                    fileItem: file,
                  ));
                },
                child: SizedBox(
                    width: 86,
                    height: 96,
                    child: ClipRRect(
                        borderRadius: BorderRadius.circular(4),
                        child: Image.asset('assets/images/icons/pdf.png')))),
          ),
          Expanded(
              flex: 1,
              child: Column(
                  mainAxisAlignment: MainAxisAlignment.spaceBetween,
                  children: [
                    Container(
                      margin: const EdgeInsets.only(bottom: 24),
                      alignment: Alignment.centerLeft,
                      child: SizedBox(
                        child: Text(file.title,
                            overflow: TextOverflow.ellipsis,
                            maxLines: 2,
                            style: TextStyle(
                              fontSize: 14,
                              color: Colors.grey[800],
                              fontWeight: FontWeight.bold,
                            )),
                      ),
                    ),
                    Container(
                        alignment: Alignment.centerRight,
                        margin: const EdgeInsets.only(bottom: 4, left: 12),
                        child: Row(
                            mainAxisAlignment: MainAxisAlignment.end,
                            children: [
                              SizedBox(
                                  child: Text(file.size,
                                      style: TextStyle(
                                        color: Colors.grey,
                                      )))
                            ])),
                  ]))
        ])),
  );
}

_buildImages(List<ImageList> imageList) {
  if (imageList.length == 1) {
    return _cover1(imageList);
  } else if (imageList.length == 2 || imageList.length == 4) {
    return _cover2(imageList);
  } else if (imageList.length == 3) {
    return _cover3(imageList);
  } else {
    return _cover4(imageList);
  }
}

Widget _videoCover(Video video) {
  int height = video.height;
  int width = video.width;
  double finalWidth;
  double finaHeight;
  if (height / width < 1) {
    finalWidth = 280;
    finaHeight = (280 * height) / width;
    if (finaHeight <= 160) {
      finaHeight = 160;
    }
  } else {
    finaHeight = 280;
    finalWidth = (280 * width) / height;
    if (finalWidth <= 160) {
      finalWidth = 160;
    }
  }
  // 视频
  return Container(
    margin: const EdgeInsets.only(top: 8),
    width: finalWidth,
    height: finaHeight,
    decoration: BoxDecoration(
      borderRadius: BorderRadius.circular(4),
      image: DecorationImage(
        fit: BoxFit.cover,
        image: NetworkImage(video.coverUrl),
      ),
    ),
    child: Icon(
      Icons.play_circle_fill,
      color: Colors.grey[500],
      size: WcaoTheme.fsBase * 4,
    ),
  );
}

// /// 1张
Widget _cover1(List<ImageList> imageList) {
  double height = 20;
  double width = 20;
  double finalWidth;
  double finaHeight;
  if (height / width < 1) {
    finalWidth = 250;
    finaHeight = (250 * height) / width;
    if (finaHeight <= 90) {
      finaHeight = 90;
    }
  } else {
    finaHeight = 250;
    finalWidth = (250 * width) / height;
    if (finalWidth <= 90) {
      finalWidth = 90;
    }
  }
  return Container(
    margin: const EdgeInsets.only(top: 8),
    child: InkWell(
        onTap: () {
          Get.to(PictureOverview(defaultIndex: 0, imageItems: imageList));
        },
        child: SizedBox(
            width: finalWidth,
            height: finaHeight,
            child: ClipRRect(
              borderRadius: BorderRadius.circular(4),
              child: CgqUtils.imageCache(imageList[0].url, fit: BoxFit.cover),
            ))),
  );
}

/// 2张或者4张
Widget _cover2(List<ImageList> imageList) {
  return Container(
    margin: const EdgeInsets.only(top: 8),
    child: Wrap(
      spacing: 4,
      runSpacing: 4,
      children: imageList
          .asMap()
          .entries
          .map((e) => InkWell(
              onTap: () {
                Get.to(PictureOverview(
                    defaultIndex: e.key, imageItems: imageList));
              },
              child: SizedBox(
                width: 124,
                height: 124,
                child: ClipRRect(
                  borderRadius: BorderRadius.circular(4),
                  child: CgqUtils.imageCache(
                    e.value.url,
                    fit: BoxFit.cover,
                  ),
                ),
              )))
          .toList(),
    ),
  );
}

//三张
Widget _cover3(List<ImageList> imageList) {
  return Container(
    margin: const EdgeInsets.only(top: 8),
    child: Row(children: [
      Container(
        margin: const EdgeInsets.only(right: 4),
        child: InkWell(
          child: SizedBox(
              width: 174,
              height: 174,
              child: ClipRRect(
                borderRadius: BorderRadius.circular(4),
                child: CgqUtils.imageCache(imageList[0].url, fit: BoxFit.cover),
              )),
          onTap: () {
            Get.to(PictureOverview(defaultIndex: 0, imageItems: imageList));
          },
        ),
      ),
      Column(children: [
        Container(
          margin: const EdgeInsets.only(bottom: 4),
          child: InkWell(
            child: SizedBox(
                width: 85,
                height: 85,
                child: ClipRRect(
                  borderRadius: BorderRadius.circular(4),
                  child:
                      CgqUtils.imageCache(imageList[1].url, fit: BoxFit.cover),
                )),
            onTap: () {
              Get.to(PictureOverview(defaultIndex: 1, imageItems: imageList));
            },
          ),
        ),
        Container(
          child: InkWell(
            child: SizedBox(
                width: 85,
                height: 85,
                child: ClipRRect(
                  borderRadius: BorderRadius.circular(4),
                  child:
                      CgqUtils.imageCache(imageList[2].url, fit: BoxFit.cover),
                )),
            onTap: () {
              Get.to(PictureOverview(defaultIndex: 2, imageItems: imageList));
            },
          ),
        ),
      ])
    ]),
  );
}

//5张以上
Widget _cover4(List<ImageList> imageList) {
  return Container(
    margin: const EdgeInsets.only(top: 8),
    child: Wrap(
      spacing: 4,
      runSpacing: 4,
      children: imageList
          .asMap()
          .entries
          .map((e) => InkWell(
              onTap: () {
                Get.to(PictureOverview(
                    defaultIndex: e.key, imageItems: imageList));
              },
              child: SizedBox(
                width: 86,
                height: 86,
                child: ClipRRect(
                  borderRadius: BorderRadius.circular(4),
                  child: CgqUtils.imageCache(e.value.url, fit: BoxFit.cover),
                ),
              )))
          .toList(),
    ),
  );
}

Row iconText(IconData icondata, String text) {
  return Row(
    crossAxisAlignment: CrossAxisAlignment.end,
    children: [
      Icon(
        icondata,
        color: WcaoTheme.secondary,
        size: WcaoTheme.fsXl,
      ),
      Padding(
        padding: const EdgeInsets.only(left: 2),
        child: Text(
          text,
          style: TextStyle(color: WcaoTheme.secondary),
        ),
      )
    ],
  );
}
